<?php

namespace app\store\controller;

use app\common\model\FosterGoods;
use app\common\model\FosterGoodsCategory;
use app\common\model\GoodsCategory;
use app\common\model\GoodsType;
use app\common\model\Spec;
use app\common\model\SpecItem;
use app\common\model\Wallet;
use app\common\util\AdminException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Goods extends Base
{
    //商品列表
    public function goods_list()
    {
        // 搜索条件
        $where[] = ['store_id', '=', $this->dianpu_id];
        $inc_type = input('inc_type',1);//1出售中2仓库中
        if ($inc_type==1){
            $where[] = ['is_on_sale', '=', 1];
        }else{
            $where[] = ['is_on_sale', '<>', 1];
        }
        $keyword = input('keyword');
        if ($keyword) {
            $where[] = ['goods_name|goods_sn', 'like', "%$keyword%"];
        }
        $goods = new \app\common\model\Goods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query' => [ 'keyword' => $keyword,'inc_type' => $inc_type],
            'list_rows' => $this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //添加编辑商品
    public function add_edit_goods()
    {
        $goods_id = input('goods_id');
        $goods = new \app\common\model\Goods();
        $images=[];
        if ($goods_id) {
            $info = $goods->find($goods_id);
            if ($info['goods_images']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_images'] as $image){
                    $pathInfo=pathinfo($image['image_url']);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image['image_url'];
                    $images[]=$map;
                }
            }
        } else {
            $info['is_on_sale'] = 1;
            $info['goods_type'] = 1;
        }
        if (IS_POST) {
            $data = input('post.');
            try {
                validate(\app\store\validate\Goods::class)->batch(true)->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                $values = array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            //发布商品是否需要审核逻辑
            if ($this->store['goods_examine']==1){//需要审核
                $data['is_on_sale'] = -1;
                $inc_type=2;
            }else{
                $data['is_on_sale'] = 1;
                $inc_type=1;
            }
            $data['store_id'] = $this->dianpu_id;
            if ($goods_id) {
                $res = $info->save($data);
                $goodsModel = $info;
            } else {
                $res = $goods->save($data);
                $goodsModel = $goods;
            }
            if ($res) {
                storeLog($goods_id ? "编辑商品" : "添加商品");
                $goodsModel->afterSave($goodsModel->goods_id);
                $data['url']=url('Goods/goods_list',['inc_type'=>$inc_type])->build();
                throw new AdminException('操作成功',1,$data);
            } else {
                throw new AdminException('操作失败');
            }
        }
        $cat_list = GoodsCategory::where("parent_id", 0)->select();
        $cat_list2 = [];
        if ($info['cat_id_2']){
            //查出二级分类
            $cat_list2 = GoodsCategory::where("parent_id",$info['cat_id_1'])->select();
        }
        $goodsType = GoodsType::select();
        View::assign('info', $info);
        View::assign('cat_list', $cat_list);
        View::assign('cat_list2', $cat_list2);
        View::assign('goodsType', $goodsType);
        View::assign('images', $images);
        return view();
    }
    //删除商品
    public function del_goods()
    {
        $ids = input('post.ids', '');
        if (empty($ids)) {
            throw new AdminException('请选择数据');
        }
        $ids_arr = implode(',', $ids);
        $goods_ids = rtrim($ids_arr, ",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('order_goods')->whereIn('goods_id', $goods_ids)->group('goods_id')->column('goods_id');
        if ($ordergoods_count) {
            $goods_count_ids = implode(',', $ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }

        // 删除此商品
        Db::name("goods")->whereIn('goods_id', $goods_ids)->delete();  //商品表
//        Db::name("cart")->whereIn('goods_id', $goods_ids)->delete();  // 购物车
        Db::name("goods_images")->whereIn('goods_id', $goods_ids)->delete();  //商品相册
        Db::name("spec_goods_price")->whereIn('goods_id', $goods_ids)->delete();  //商品规格
        Db::name("spec_image")->whereIn('goods_id', $goods_ids)->delete();  //商品规格图片
        Db::name("goods_collect")->whereIn('goods_id', $goods_ids)->delete();  //商品收藏
        Db::name("goods_visit")->whereIn('goods_id', $goods_ids)->delete();  //浏览足迹
        storeLog("删除商品");
        throw new AdminException('操作成功',1);
    }
    //商品评论列表
    public function goods_comment_list(){
        // 搜索条件
        $where[] = ['store_id', '=', $this->dianpu_id];
        $search_type = input('search_type');
        $search_key = input('search_key');
        if ($search_key){
            if ($search_type=='mobile'){
                $ids=Db::name('users')->whereLike('mobile',"%$search_key%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }else{
                $ids=Db::name('users')->whereLike('realname',"%$search_key%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }
        }
        $list = Comment::where($where)
            ->whereBetween('add_time',"$this->begin,$this->end")
            ->order('id desc')
            ->paginate([
                'query'=>['search_type'=>$search_type,'search_key'=>$search_key],
                'list_rows'=>$this->page_size
            ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //商品上/下架
    public function sale_goods(){
        $goods_id = input('goods_id');
        $is_on_sale = input('is_on_sale');
        if (empty($goods_id)){
            throw new AdminException('参数错误');
        }
        if (!in_array($is_on_sale,[0,1])){
            throw new AdminException('提交参数有误');
        }
        $goods = new \app\common\model\Goods();
        $info = $goods->find($goods_id);
        if (empty($info) || $info['store_id']!=$this->dianpu_id){
            throw new AdminException('商品不存在');
        }
        if ($info['goods_state']!=1){
            throw new AdminException('商品审核通过后才可进行上/下架');
        }
        $info->is_on_sale=$is_on_sale;
        $info->save();
        throw new AdminException('操作成功');
    }
    //删除规格项
    public function deleteSpec()
    {
        $id = input('id/d');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $Spec = new Spec();
        $spec = $Spec->find($id);
        if ($spec->isEmpty()){
            return json(['code' => 0, 'msg' => '删除失败,规格不存在!']);
        }else{
            $spec->delete();
            return json(['code' => 1, 'msg' => '删除成功']);
        }
    }
    //删除规格值
    public function deleteSpecItem()
    {
        $id = input('id/d');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $SpeItem = new SpecItem();
        $spec_item = $SpeItem->find($id);
        if ($spec_item->isEmpty()){
            return json(['code' => 0, 'msg' => '删除失败,规格不存在!']);
        }else{
            $spec_item->delete();
            return json(['code' => 1, 'msg' => '删除成功']);
        }
    }
    /**
     * 获取商品模型下拉列表
     */
    public function ajaxGetGoodsTypeList($type_id)
    {
        $GoodsType = new GoodsType();
        $goods_type = $GoodsType->select();

        $html = '<option value="0">选择商品模型';
        foreach ($goods_type as $v){
            $html .= "<option value='{$v['id']}'";
            if($type_id == $v['id']){
                $html .= ' selected="selected" ';
            }
            $html .= ">{$v['name']}</option>";
        }
        exit(json_encode($html, JSON_UNESCAPED_UNICODE));
    }
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect()
    {
        $goods_id = input('goods_id/d', 0);
        $type_id = input('type_id/d', 0);
        $specList = Db::name('spec')->where("type_id", $type_id)->order('sort asc')->select()->toArray();
        foreach ($specList as $k => $v){
            $spec_item=Db::name('spec_item')->where("spec_id" , $v['id'])->order('id')->column('item','id'); // 获取规格项
            $specList[$k]['spec_item'] = $spec_item;
        }
        $items_id = Db::name('spec_goods_price')->where('goods_id', $goods_id)->value("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);
//        dump($specList);
//        halt($items_ids);
        // 获取商品规格图片
        if ($goods_id) {
            $specImageList = Db::name('spec_image')->where("goods_id", $goods_id)->column('src','spec_image_id');
            View::assign('specImageList', $specImageList);
        }
        View::assign('items_ids', $items_ids);
        View::assign('specList', $specList);
        return view('ajax_spec_select');
    }
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput(){
        $GoodsLogic = new \app\common\model\Goods();
        $goods_id = input('goods_id/d') ? input('goods_id/d') : 0;
        $str = $GoodsLogic->getSpecInput($goods_id ,input('post.spec_arr/a',[[]]));
        exit($str);
    }
    /**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = input('filename','');
        Db::name('goods_images')->where("image_url",$path)->delete();
    }
    //认养商品列表
    public function foster_goods_list(){
        // 搜索条件
        $where[] = ['store_id', '=', $this->dianpu_id];
        $inc_type = input('inc_type',1);//1出售中2仓库中
        if ($inc_type==1){
            $where[] = ['is_on_sale', '=', 1];
        }else{
            $where[] = ['is_on_sale', '<>', 1];
        }
        $keyword = input('keyword');
        if ($keyword){
            $where[]=['goods_name','like',"%$keyword%"];
        }
        $goods=new FosterGoods();
        $list = $goods->where($where)->order('goods_id desc')->paginate([
            'query'=>['inc_type'=>$inc_type,'keyword'=>$keyword],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //商品上/下架
    public function sale_foster(){
        $goods_id = input('goods_id');
        $is_on_sale = input('is_on_sale');
        if (empty($goods_id)){
            throw new AdminException('参数错误');
        }
        if (!in_array($is_on_sale,[0,1])){
            throw new AdminException('提交参数有误');
        }
        $goods = new FosterGoods();
        $info = $goods->find($goods_id);
        if (empty($info) || $info['store_id']!=$this->dianpu_id){
            throw new AdminException('商品不存在');
        }
        if ($info['goods_state']!=1){
            throw new AdminException('商品审核通过后才可进行上/下架');
        }
        $info->is_on_sale=$is_on_sale;
        $info->save();
        throw new AdminException('操作成功',1);
    }
    //添加编辑认养商品
    public function add_edit_foster_goods(){
        $goods_id=input('goods_id');
        $images=$foster_goods_extra=[];
        $goods=new FosterGoods();
        if ($goods_id){
            $info=$goods->find($goods_id);
            if ($info['store_id']!=$this->dianpu_id){
                $this->error('商品不存在');
            }
            if ($info['goods_imgs']){
                $arr=['mp4','3gp'];
                foreach ($info['goods_imgs'] as $image){
                    $pathInfo=pathinfo($image);
                    $fileValueSuffix=strtolower($pathInfo['extension']);
                    if (in_array($fileValueSuffix,$arr)){
                        $map['type']='video';
                    }else{
                        $map['type']='image';
                    }
                    $map['src']=$image;
                    $images[]=$map;
                }
            }
            if ($info['extra_text']){
                foreach ($info['extra_text'] as $ex){
                    $map['lq_time']=date('Y-m-d H:i:s',$ex['lq_time']);
                    $map['number']=$ex['number'];
                    $map['id']=date('YmdHis').rand(1000,9999);
                    $foster_goods_extra[]=$map;
                }
            }
        }else{
            $info['is_on_sale']=1;
        }
        if (IS_POST){
            $data=input('post.');
            try {
                validate(\app\store\validate\FosterGoods::class)->batch(true)->check($data);
            }catch (ValidateException $e){
                $error=$e->getError();
                $values=array_values($error);
                $result['result']=$error;
                throw new AdminException($values[0],10,$result);
            }
            $extra_wid = input('extra_wid');
            $extra_text = input('extra_text/a');
            if ($extra_text && $extra_wid>0){
                foreach ($extra_text as $key => $item){
                    if (empty($item["lq_time"])){
                        $msg=sprintf('请选择领取时间');
                        throw new AdminException($msg);
                    }
                    if (empty($item["number"])){
                        $msg=sprintf('请输入金额');
                        throw new AdminException($msg);
                    }
                    $extra_text[$key]['lq_time']=strtotime($item['lq_time']);
                }
                $data['extra_text']=$extra_text;
            }else{
                $data['extra_text']=[];
            }
            //发布商品是否需要审核逻辑
            if ($this->store['goods_examine']==1){//需要审核
                $data['is_on_sale'] = -1;
                $inc_type=2;
            }else{
                $data['is_on_sale'] = 1;
                $inc_type=1;
            }
            $data['store_id'] = $this->dianpu_id;
            if ($goods_id){
                $res=$info->save($data);
                $new_goods_id=$goods_id;
            }else{
                $res=$goods->save($data);
                $new_goods_id=$goods->goods_id;
            }
            if ($res){
                $goods_sn = "CSMC".str_pad($new_goods_id,7,"0",STR_PAD_LEFT);
                Db::name('foster_goods')->where("goods_id = $new_goods_id and goods_sn = ''")->save(["goods_sn"=>$goods_sn]); // 根据条件更新记录
                storeLog($goods_id?"编辑认养商品":"添加认养商品");
                $data['url']=url('Goods/foster_goods_list',['inc_type'=>$inc_type])->build();
                throw new AdminException('操作成功',1,$data);
            }else{
                throw new AdminException('操作失败');
            }
        }
        $wallet=Wallet::where('1=1')->column('id,name');
        $cate_list=FosterGoodsCategory::where('1=1')->column('id,name');
        View::assign('cate_list', $cate_list);
        View::assign('wallet', $wallet);
        View::assign('info', $info);
        View::assign('images', $images);
        View::assign('foster_goods_extra', $foster_goods_extra);
        return view();
    }
    //删除认养商品
    public function delFosterGoods()
    {
        $ids = input('post.ids','');
        if (empty($ids)){
            throw new AdminException('请选择数据');
        }
        $ids_arr=implode(',',$ids);
        $goods_ids = rtrim($ids_arr,",");
        // 判断此商品是否有订单
        $ordergoods_count = Db::name('foster_order')->whereIn('goods_id',$goods_ids)->group('goods_id')->column('goods_id');
        if($ordergoods_count) {
            $goods_count_ids = implode(',',$ordergoods_count);
            throw new AdminException("ID为【{$goods_count_ids}】的商品有订单,不得删除!");
        }
        // 删除此商品
        Db::name("foster_goods")->whereIn('goods_id',$goods_ids)->delete();  //商品表
        storeLog("删除认养商品");
        throw new AdminException('操作成功',1);
    }
}
